﻿document.getElementById("searchBtn").onclick = function () {
    self.location.href = "/shop/search?keyword=" + document.getElementById("searchKeyWordInput").value;
}
document.getElementById("searchKeyWordInput").onkeyup = getKeyWord
var oldkeyword = "";
var toolTipText = false;
function getKeyWord() {
    if (_toolTipPanle.style.display == 'block') {

        if (window.event.keyCode == 38) {
            selectToolTip(-1)
        } else if (window.event.keyCode == 40) {
            selectToolTip(1)
        } else if (window.event.keyCode == 32 && toolTipText == true) {

            _keyWordInput.value = $(_toolTipPanle.children(0).children)[selectToolTip.selectedIndex].innerHTML;
            toolTipText = false;
        } else {
            toolTipText = false;
        }
    }
    var _keyword = _keyWordInput.value;

    if (_keyword == "") { oldkeyword = ""; _toolTipPanle.style.display = "none"; return; }
    if (oldkeyword == _keyword) { return }

    $.get("/sitePublic/tooltipKeyWord?keyword=" + encodeURI(_keyword), showKeyWord);

    oldkeyword = _keyword;

}
function selectToolTip(step) {
    var _li = $(_toolTipPanle.children(0).children);
    var _newSelectedIndex;

    if (selectToolTip.selectedIndex + step < 0) {
        _newSelectedIndex = _li.length - 1;
    } else if (selectToolTip.selectedIndex + step >= _li.length) {
        _newSelectedIndex = 0;
    } else {
        _newSelectedIndex = selectToolTip.selectedIndex + step;
    }
    if (selectToolTip.selectedIndex != -1) {
        $(_li[selectToolTip.selectedIndex]).removeClass("hover");

    }
    $(_li[_newSelectedIndex]).addClass("hover");
    selectToolTip.selectedIndex = _newSelectedIndex;
    toolTipText = true;


}
function showKeyWord(json) {


    if (json.length == 0) { _toolTipPanle.style.display = "none"; return }
    //排序
    json.sort(function (a, b) { return (a.value.length - b.value.length) });
    if (json[0].value == _keyWordInput.value) {
        json.shift()
    }

    _toolTipPanle.children(0).innerHTML = "";
    var _HTMLstr = new Array();

    for (var i = 0; i < json.length; i++) {
        _HTMLstr.push("<li>" + json[i].value + "</li>");
    }
    _toolTipPanle.children(0).innerHTML = _HTMLstr.join("");
    _toolTipPanle.style.display = "block";
    //定义选择状态
    selectToolTip.selectedIndex = -1;
}
var _keyWordInput = document.getElementById("searchKeyWordInput");
var _toolTipPanle = document.getElementById("toolTipKeyWord");
_toolTipPanle.children(0).onclick = function () {
    _keyWordInput.value = event.srcElement.innerHTML;
    _toolTipPanle.style.display = "none";
}